package jkoa.middleware;

import java.util.function.Consumer;

import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import cn.hutool.core.io.FileUtil;
import cn.hutool.setting.Setting;
import jkoa.core.Context;
import jkoa.core.Middleware;
import jkoa.core.Next;

public class RedisMiddleware implements Middleware {
    private RedisTemplate<String, Object> redisTemplate;

    public RedisMiddleware() {
        String redisConfigPath = "redis.properties";
        if (FileUtil.exist(redisConfigPath)) {
            Setting setting = new Setting(redisConfigPath);
            String host = setting.getStr("redis.host", "localhost");
            int port = setting.getInt("redis.port", 6379);

            redisTemplate = new RedisTemplate<>();
            redisTemplate.setKeySerializer(new StringRedisSerializer());
            redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<>(Object.class));
            redisTemplate.setConnectionFactory(redisConnectionFactory(host, port));
        }
    }

    private RedisConnectionFactory redisConnectionFactory(String host, int port) {
        LettuceConnectionFactory factory = new LettuceConnectionFactory(host, port);
        factory.afterPropertiesSet();
        return factory;
    }

    @Override
    public void handle(Context ctx, Next next) {
        // 这里可以处理与 Redis 相关的请求
        next.execute(ctx);
    }
}